﻿using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.QrCode.Internal;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
using ZXing.QrCode;
using System.Runtime.InteropServices;
using System.Drawing.Printing;
using System.Runtime.CompilerServices;

namespace Rmac.Uitls
{
    public class PrintUtils
    {
        Bitmap QrImg { set; get; }
        private int Width { set; get; }
        private int Height { set; get; }
        private string QrConent { set; get; }


        public PrintUtils(string content,int width = 260,int height = 260)
        {
            QrConent = content;
            Width = width;
            Height = height;
            GenerateQrCode(QrConent,Width,Height);
        }

        #region IntPtr Gp_IntPtr
        /*
        //private IntPtr Gp_IntPtr;                   //驱动打印句柄
        private libUsbContorl.UsbOperation NewUsb = new libUsbContorl.UsbOperation();

        public void Print()
        {
            byte[] SendBmpData;
            uint sendWidth = 0;     //实际发送的宽
            uint sendHeight = 0;    //实际发送的高
            byte[] setHBit = { 0x80, 0x40, 0x30, 0x10, 0x08, 0x04, 0x02, 0x01 };    //算法辅助 置1
            byte[] clsLBit = { 0x7F, 0xBF, 0xDF, 0xEF, 0xF7, 0xFB, 0xFD, 0xFE };    //算法辅助 置0

            sendWidth = (uint)getimage.Width;      //实际发送的宽
            sendHeight = (uint)getimage.Height;    //实际发送的高

            if (getimage.Height % 8 != 0)
                sendHeight = sendHeight + 8 - sendHeight % 8;
            if (getimage.Width % 8 != 0)
                sendWidth = sendWidth + 8 - sendWidth % 8;

            Bitmap getbmp = new Bitmap(getimage);
            //                     Bitmap BmpCopy = new Bitmap(getimage.Width, getimage.Height, PixelFormat.Format32bppArgb);

            SendBmpData = new byte[sendWidth * sendHeight / 8];
            memset(SendBmpData, 0xff, (int)(sendWidth * sendHeight / 8));//0XFF为全白

            #region 求灰度平均值
            Double redSum = 0, geedSum = 0, blueSum = 0;
            Double total = sendWidth * sendHeight;
            byte[] huiduData = new byte[sendWidth * sendHeight / 8];
            for (int i = 0; i < getimage.Width; i++)
            {
                int ta = 0, tr = 0, tg = 0, tb = 0;
                for (int j = 0; j < getimage.Height; j++)
                {
                    System.Drawing.Color getcolor = getbmp.GetPixel(i, j);//取每个点颜色
                    ta = getcolor.A;
                    tr = getcolor.R;
                    tg = getcolor.G;
                    tb = getcolor.B;
                    redSum += ta;
                    geedSum += tg;
                    blueSum += tb;
                }
            }
            int meanr = (int)(redSum / total);
            int meang = (int)(geedSum / total);
            int meanb = (int)(blueSum / total);
            #endregion 求灰度平均值

            for (int j = 0; j < getimage.Height; j++)
            {
                for (int i = 0; i < getimage.Width; i++)
                {
                    System.Drawing.Color getcolor = getbmp.GetPixel(i, j);//取每个点颜色
                    if ((getcolor.R * 0.299) + (getcolor.G * 0.587) + (getcolor.B * 0.114) < ((meanr * 0.299) + (meang * 0.587) + (meanb * 0.114)))//颜色转灰度(可调 0-255)
                        SendBmpData[j * sendWidth / 8 + i / 8] &= clsLBit[i % 8];
                }
            }
            NewUsb.FindUSBPrinter();
            for (int i = 0; i < NewUsb.USBPortCount; i++)
            {
                if (NewUsb.LinkUSB(i))
                {
                    SendData2USB("CLS\n");
                    SendData2USB("SIZE " + (sendWidth / 8 + 4).ToString() + " mm," + (sendHeight / 8 + 3).ToString() + " mm\n");
                    SendData2USB("BITMAP 24,20," + (sendWidth / 8).ToString() + "," + sendHeight.ToString() + ",0,");
                    SendData2USB(SendBmpData);
                    SendData2USB("PRINT 1\n");
                    NewUsb.CloseUSBPort();
                }
            }
        }
        private void SendData2USB(byte[] str)
        {
            NewUsb.SendData2USB(str, str.Length);
        }
        private void SendData2USB(string str)
        {
            byte[] by_SendData = System.Text.Encoding.GetEncoding(54936).GetBytes(str);
            SendData2USB(by_SendData);
        }

        /// <summary>
        /// 重写metset
        /// </summary>
        /// <param name="buf">设置的数组</param>
        /// <param name="val">设置的数据</param>
        /// <param name="size">数据长度</param>
        /// <returns>void</returns>     
        public void memset(byte[] buf, byte val, int size)
        {
            int i;
            for (i = 0; i < size; i++)
                buf[i] = val;
        }
        */
        #endregion

        private void GenerateQrCode(string content, int width, int height)
        {
            var writer = new BarcodeWriterPixelData
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Width = width,
                    Height = height,
                    Margin = 0
                }
            };
            var pixelData = writer.Write(content);
            QrImg = new Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppArgb);
            var bitmapData = QrImg.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), ImageLockMode.WriteOnly, QrImg.PixelFormat);
            Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
            QrImg.UnlockBits(bitmapData);
        }

        /// <summary>
         /// 调用本地默认打印机进行打印二维码
         /// </summary>
        public void PrintDocument()
        {
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
            var printDocument = new PrintDocument();
            printDocument.PrinterSettings.PrinterName = sDefault;//驱动名称
                                                                 //             
            printDocument.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
            try
            {
                //打印
                printDocument.Print();
            }
            catch (InvalidPrinterException)
            {

            }
            finally
            {
                printDocument.Dispose();
            }
        }

        /// <summary>
        /// 打印绘制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            //System.Drawing.Font titleFont = new System.Drawing.Font("宋体", 9, FontStyle.Bold);//标题字体           

            //System.Drawing.Font fntTxt = new System.Drawing.Font("宋体", 9, FontStyle.Regular);//正文文字           

            //System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);//画刷           

            //Pen pen = new Pen(System.Drawing.Color.Black); //线条颜色           

            //System.Drawing.Point po = new System.Drawing.Point(10, 10);

            e.Graphics.DrawImage(QrImg, e.PageBounds);//打印内容
        }

    }
}
